#-*- encoding:utf8 -*-

from django import http
from django.shortcuts import render
from django.contrib import auth
import json

from accounts import models as accounts_models

def login1(request):
    context = {u'username' :u''}
    if request.POST:
        context = {}
        username = request.POST.get("form-username")
        password = request.POST.get("form-password")
        user = auth.authenticate(username=username,password=password)

        if user:
            if not user.is_active:
                context[u'message'] = u'用户被冻结无法登陆！'
                context[u'username'] = username
            else:
                auth.login(request,user)
                next_url = request.GET.get(u'next','/')
                return http.HttpResponseRedirect(next_url)
        else:
            context[u'message'] = u'用户名称或者密码不正确!'
            context[u'username'] = username

        return render(request,u'login.html',context)
    return render(request,u'login.html',context)

def login(request):
    username = request.GET.get(u"username")
    password = request.REQUEST.get(u"password")
    user = auth.authenticate(username=username,password=password)
    result = []
    if user:
        if not user.is_active:
            result = {
                u'username' : username,
                u'message' : u'not active'
            }
        else:
            auth.login(request,user)
            for group in request.user.groups.all():
                g = group.school_item()
                g[u'objects'] = [{u'id':gobj.object.id,u'text':gobj.object.text} for gobj in group.groupnavigatorobject_set.all()]
                result.append(g)
    return http.HttpResponse(json.dumps(result),content_type=u'application/json')